package config

import (
	"flag"
	log "github.com/micro/go-micro/v2/logger"
	"gopkg.in/ini.v1"
)

//启动参数
var (
	ResourcesPath = flag.String("resources", "./resources", "-config resources path")
	Env           = flag.String("env", "dev", "-env:dev/test/uat/prod")
)

type NacosConfig struct {
	NacosAddrs  string `ini:"nacos_addrs"`
	NacosNamespaceId string `ini:"nacos_namespace_id"`
	NacosDataId      string `ini:"nacos_data_id"`
	NacosGroup       string `ini:"nacos_group"`
}

type EnvConfig struct {
	Nacos NacosConfig `ini:"nacos"`
}

func GetConfigFile() string {
	resourcesPath := *ResourcesPath
	path := resourcesPath + "/service.ini"
	return path
}

func GetEnvConfigFile() string {
	resourcesPath := *ResourcesPath
	env := *Env
	path := resourcesPath + "/config-" + env + ".ini"
	return path
}

var envConfig = new(EnvConfig)

func GetEnvConfig() *EnvConfig {
	return envConfig
}

func LoadNacosConfig() *NacosConfig {
	return &envConfig.Nacos
}

func LoadEnvConfig() *EnvConfig {
	path := GetEnvConfigFile()
	cfg, err := ini.Load(path)

	if err != nil {
		log.Fatal("InitNacosConfig: ", path, ".  config err: ", err.Error())
	}
	err = cfg.MapTo(envConfig)
	if err != nil {
		log.Fatal("InitNacosConfig: ", path, ".  MapTo err: ", err.Error())
	}
	log.Info("Nacos Config File", path, envConfig)
	return envConfig
}
